package com.irdstudio.efp.esb.api.service.sed.ploaninfo;

import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.efp.console.common.ConsoleConstant;
import com.irdstudio.efp.esb.api.bean.sed.ploaninfo.RepayDetailArr;
import com.irdstudio.efp.esb.api.bean.sed.ploaninfo.ReqPersonalRepayDetail;
import com.irdstudio.efp.esb.api.bean.sed.ploaninfo.RespPersonalRepayDetail;
import com.irdstudio.efp.esb.api.common.sed.SetlType;
import com.irdstudio.efp.esb.api.util.TransferQueryParams;
import com.irdstudio.efp.esb.common.constant.RespRetCode;
import com.irdstudio.efp.esb.service.bo.resp.hj.HjRpayDetaillInfArry;
import com.irdstudio.efp.esb.service.bo.resp.hj.RepayInfoQueryRespBean;
import com.irdstudio.efp.loan.service.vo.AccLoanVO;
import com.irdstudio.efp.loan.service.vo.LoanRepayDetailVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
* 普税贷产品对税e贷产品的此部分代码做了复用
* 说明：为了保证功能的复用性、提升开发的工作效率，对该代码进行了复用
* 评估是否会影响线上功能：否
* 评估时间：2020/5/25
* 处理方案：保留复用
*/
/**
 * 需求编号：【2019D0519】
 * 问题编号：【】
 * @author xiaojunhui
 * @version 0.1
 * @description TODO
 * @date 2019/5/9 12:27
 */
@Service
public class PersonalRepayDetailService {

    private static Logger logger = LoggerFactory.getLogger(PersonalRepayDetailService.class);

    /**
     * 预言借据号为空
     */
    private final Predicate<ReqPersonalRepayDetail> billNoPredicate=(reqPersonalRepayDetail)-> StringUtils.isEmpty(reqPersonalRepayDetail.getBillNo());

    /**
     * 预言还款申请流水号为空
     */
    private final Predicate<ReqPersonalRepayDetail> setlSeqPredicate=(reqPersonalRepayDetail)-> StringUtils.isEmpty(reqPersonalRepayDetail.getSetlSeq());

    /**
     * 预言还款类型为空
     */
    private final Predicate<ReqPersonalRepayDetail> setlTypePredicate1=(reqPersonalRepayDetail)-> StringUtils.isEmpty(reqPersonalRepayDetail.getSetlType());
    /**
     * 预言还款类型非法
     */
    private final Predicate<ReqPersonalRepayDetail> setlTypePredicate2=(reqPersonalRepayDetail)-> {
        //判断是否在还款类型数组中
        return !Optional.ofNullable(SetlType.getEnum(reqPersonalRepayDetail.getSetlType())).isPresent();
    };


    /**
     * 根据规则封装查询参数
     * 1.借据号跟流水号不能全为空
     * 2.借据号不为空的情况下，还款类型可以输入符合定义的类型
     */
    public final TransferQueryParams<ReqPersonalRepayDetail, LoanRepayDetailVO> transferQueryParams=(reqPersonalRepayDetail)->{

        LoanRepayDetailVO repayDetailVO=new LoanRepayDetailVO();
        if (billNoPredicate.test(reqPersonalRepayDetail)&&setlSeqPredicate.test(reqPersonalRepayDetail)) {
            throw new BizException("借据号和还款申请流水号不能都为空");
        }
        if (!billNoPredicate.test(reqPersonalRepayDetail)) {
            if (!setlTypePredicate1.test(reqPersonalRepayDetail)) {
                if (setlTypePredicate2.test(reqPersonalRepayDetail)) {
                    throw new BizException("还款类型非法");
                }
            }
        }
        if (!billNoPredicate.test(reqPersonalRepayDetail)) {
            repayDetailVO.setLoanNo(reqPersonalRepayDetail.getBillNo());
        }
        if (!setlSeqPredicate.test(reqPersonalRepayDetail)){
            repayDetailVO.setSetlSeq(reqPersonalRepayDetail.getSetlSeq());
        }
        if (!setlTypePredicate1.test(reqPersonalRepayDetail)) {
            if (!setlTypePredicate2.test(reqPersonalRepayDetail)) {
                repayDetailVO.setSetlTyp(reqPersonalRepayDetail.getSetlType());
            }
        }
        return repayDetailVO;
    };


    /**
     * 设置还款计划中还款明细的数据
     */
    private RepayDetailArr c2DetailArr(LoanRepayDetailVO loanRepayDetailVO){
        RepayDetailArr repayDetailArr = new RepayDetailArr();
        //还款申请流水号
        repayDetailArr.setSetlSeq(loanRepayDetailVO.getSetlSeq());
        //剩余本金
       // repayDetailArr.setPsPrin(loanRepayDetailVO.getPsRemPrcp());
        //还款期数
        //repayDetailArr.setSetlTerm(loanRepayDetailVO.getRepayTerm());
        //还款类型
        repayDetailArr.setSetlType(loanRepayDetailVO.getSetlTyp());
        //执行利率
        repayDetailArr.setEndDt(loanRepayDetailVO.getIntRat());
        //还款总计金额
        repayDetailArr.setState(loanRepayDetailVO.getTotalAmt());
        //归还本金
        repayDetailArr.setTermSupplyAmt(loanRepayDetailVO.getSetlOdPrcpAmt());
        //归还利息
        repayDetailArr.setsPrinAmt(loanRepayDetailVO.getSetlPsIncTaken());
        //归还罚息
        repayDetailArr.setsIntAmt(loanRepayDetailVO.getSetlOdIntAmt());
        //归还复利
        repayDetailArr.setsPenIntAmt(loanRepayDetailVO.getSetlOdCommInt());
        //归还复利的复利
        repayDetailArr.setRcylCmpdIntNrlCmpdIntAmt(BigDecimal.ZERO);
        //归还罚息的复利
        repayDetailArr.setRcylPnyIntNrlCmpdIntAmt(BigDecimal.ZERO);
        //归还费用
        repayDetailArr.setsCompIntAmt(loanRepayDetailVO.getSetlTotalFee());
        //还款账号
        repayDetailArr.setsFeeAmt(loanRepayDetailVO.getDisbAcNo());
        //还款状态
        repayDetailArr.setaPrinAmt(loanRepayDetailVO.getRpSts());
        //还款日期
        repayDetailArr.setaIntAmt(loanRepayDetailVO.getSetlApplyDt());
        //审批状态wfApprSts
        repayDetailArr.setAprvSt(loanRepayDetailVO.getWfApprSts());
        //失败原因refuseCause
        repayDetailArr.setFailRsn(loanRepayDetailVO.getRefuseCause());
        return repayDetailArr;
    }

    private RepayDetailArr c2DetailArr(HjRpayDetaillInfArry rpyDtlInfArry, List<LoanRepayDetailVO> loanRepayDetails) {
        RepayDetailArr repayDetailArr = new RepayDetailArr();
        //还款申请流水号
        String setlSeq = "";
        if (loanRepayDetails != null) {
            for (LoanRepayDetailVO loanRepayDetail : loanRepayDetails) {
                if (rpyDtlInfArry.getRpyNo().equals(loanRepayDetail.getRpyNo())) {
                    setlSeq = loanRepayDetail.getSetlSeq();
                    break;
                }
            }
        }
        repayDetailArr.setSetlSeq(StringUtils.isEmpty(setlSeq) ? rpyDtlInfArry.getRpyNo() : setlSeq);
        //剩余本金
        //repayDetailArr.setPsPrin(loanRepayDetailVO.getPsRemPrcp());
        //还款期数
        //repayDetailArr.setSetlTerm(loanRepayDetailVO.getRepayTerm());
        //还款类型
        //NS-正常回收,ER-提前回收,PO-清户,WV-豁免,PP-部分提前还款(收费),PF-提前结清收费,TR-终止
/*        01	全部提前还款		PO	全部结清
        02	部分提前还款		ER	提前部分还本
        03	只还本金不还利息		PR	部分还款（先还欠款如有剩余提前还本）
        04	正常还款		NS	正常还款
        05	按期次提前还款		PS	按期次提前还款*/

        if (StringUtils.isNotEmpty(rpyDtlInfArry.getRpyType())) {
            if ("PO".equals(rpyDtlInfArry.getRpyType())) {
                repayDetailArr.setSetlType(ConsoleConstant.REPAY_TYPE_03);
            }
            if ("ER".equals(rpyDtlInfArry.getRpyType())) {
                repayDetailArr.setSetlType(ConsoleConstant.REPAY_TYPE_02);
            }
            if ("PR".equals(rpyDtlInfArry.getRpyType())) {
                repayDetailArr.setSetlType(ConsoleConstant.REPAY_TYPE_07);
            }
            if ("PS".equals(rpyDtlInfArry.getRpyType())) {
                repayDetailArr.setSetlType(ConsoleConstant.REPAY_TYPE_06);
            }
            if ("NS".equals(rpyDtlInfArry.getRpyType())) {
                repayDetailArr.setSetlType(ConsoleConstant.REPAY_TYPE_01);
            }
            if ("WV".equals(rpyDtlInfArry.getRpyType())) {
                repayDetailArr.setSetlType(ConsoleConstant.REPAY_TYPE_09);
            }
        }
        //repayDetailArr.setSetlType(rpyDtlInfArry.getRpyType());
        //执行利率
        //repayDetailArr.setEndDt();
        //还款总计金额
        repayDetailArr.setState(rpyDtlInfArry.getRpyAmt());
        //归还本金
        repayDetailArr.setTermSupplyAmt(rpyDtlInfArry.getRcylPnpAmt());
        //归还利息
        repayDetailArr.setsPrinAmt(rpyDtlInfArry.getRcylIntAmt());
        //归还罚息
        repayDetailArr.setsIntAmt(rpyDtlInfArry.getRcylPnyIntAmt());
        //归还复利
        repayDetailArr.setsPenIntAmt(rpyDtlInfArry.getRcylCmpdIntAmt());
        //归还复利的复利
        repayDetailArr.setRcylCmpdIntNrlCmpdIntAmt(rpyDtlInfArry.getRcylCmpdIntNrlCmpdIntAmt());
        //归还罚息的复利
        repayDetailArr.setRcylPnyIntNrlCmpdIntAmt(rpyDtlInfArry.getRcylPnyIntNrlCmpdIntAmt());
        //归还费用
        repayDetailArr.setsCompIntAmt(PloaninfoUtils.getAddResult(rpyDtlInfArry.getRcylPnpAmt(), rpyDtlInfArry.getRcylIntAmt(), rpyDtlInfArry.getRcylCmpdIntAmt(), rpyDtlInfArry.getRcylPnyIntAmt(), rpyDtlInfArry.getRcylCmpdIntNrlCmpdIntAmt(), repayDetailArr.getRcylPnyIntNrlCmpdIntAmt()));
        //还款账号
        repayDetailArr.setsFeeAmt("");
        //还款状态
        repayDetailArr.setaPrinAmt(rpyDtlInfArry.getRpyAmt().doubleValue() <= 0 ? "0" : "1");
        //还款日期
        repayDetailArr.setaIntAmt(LocalDate.parse(rpyDtlInfArry.getRpyDt(), DateTimeFormatter.ofPattern("yyyyMMdd")).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        //审批状态wfApprSts
        repayDetailArr.setAprvSt(rpyDtlInfArry.getRpyAmt().doubleValue() <= 0 ? "03" : "02");
        //失败原因refuseCause
        repayDetailArr.setFailRsn("");
        return repayDetailArr;
    }

    /**
     * 处理响应信息
     * * xuehengheng(陈昂磊) 05-12 18:07:37
     * * NARRATIVE is null and REFERENCE is not null  联机      NARRATIVE is not null and REFERENCE is null 批扣
     * * xuehengheng(陈昂磊) 05-12 18:08:32
     * * 以这个判断规则区别联机还是批扣
     * *
     *
     * @param respPersonalRepayDetail 响应对象
     * @param loanRepayDetailVOs      本地的还款记录数据
     * @param accLoanVO               本地的借据信喜
     * @param repayInfoQueryRespBean  根据贷款发放号查询互金返回的贷款回收信息
     */
    public void handleResp(boolean singleQuery, RespPersonalRepayDetail respPersonalRepayDetail, List<LoanRepayDetailVO> loanRepayDetailVOs, AccLoanVO accLoanVO, RepayInfoQueryRespBean repayInfoQueryRespBean) {
        //先从本地的借据信息封装部分返回的信息
        respPersonalRepayDetail.setCertCode(accLoanVO.getCertCode());
        respPersonalRepayDetail.setCertType(accLoanVO.getCertType());
        respPersonalRepayDetail.setBillNo(accLoanVO.getBillNo());
        respPersonalRepayDetail.setCusName(accLoanVO.getCusName());
        respPersonalRepayDetail.setDnAmt(accLoanVO.getLoanAmount());
        ArrayList<RepayDetailArr> repayDetailArrs = new ArrayList<>();
        if (loanRepayDetailVOs != null && loanRepayDetailVOs.size() > 0) {
            //从本地取失败的记录，输出
            List<LoanRepayDetailVO> localFails = loanRepayDetailVOs.stream().filter(r -> !"02".equals(r.getWfApprSts())).collect(Collectors.toList());
            if (localFails != null && localFails.size() >= 1) {
                localFails.stream().forEach(r -> repayDetailArrs.add(c2DetailArr(r)));
                if (singleQuery) {
                    respPersonalRepayDetail.setRetCode(RespRetCode.SUCCESS.getCode());
                    respPersonalRepayDetail.setRetMsg("查询成功");
                    respPersonalRepayDetail.setRepayDetailArr(repayDetailArrs);
                    return;
                }
            }
//            //从本地取出还款成功的记录
//            List<LoanRepayDetailVO> localSucces = loanRepayDetailVOs.stream().filter(r -> "02".equals(r.getWfApprSts())&&!"0".equals(r.getRpSts())).collect(Collectors.toList());
//            if (localFails != null && localFails.size() > 1) {
//                for (LoanRepayDetailVO localSucce : localSucces) {
//                    //从互金中取出记录
//                    ArrayList<HjRpayDetaillInfArry> rpyDtlInfArry = repayInfoQueryRespBean.getRpyDtlInfArrys();
//                    for (HjRpayDetaillInfArry dtlInfArry : rpyDtlInfArry) {
//                        if (StringUtils.isEmpty(dtlInfArry.getRpyNo())) {
//                            continue;
//                        }
//                        if (dtlInfArry.getRpyNo().equals(localSucce.getRpyNo())) {
//                            //还款号一样
//                            if (dtlInfArry.getRpyNo().equals(localSucce.getRpyNo())) {
//                                repayDetailArrs.add(c2DetailArr(localSucce, dtlInfArry));
//                            }
//                        }
//                    }
//                }
//            }
        }
        //取互金回收成功的记录输出
        ArrayList<HjRpayDetaillInfArry> rpyDtlInfArry = repayInfoQueryRespBean.getRpyDtlInfArrys();
        if (rpyDtlInfArry != null && rpyDtlInfArry.size() > 0) {
            for (HjRpayDetaillInfArry hjRpayDetaillInfArry : rpyDtlInfArry) {
                /*if (loanRepayDetailVOs != null && loanRepayDetailVOs.size() > 0) {
                    for (LoanRepayDetailVO loanRepayDetailVO : loanRepayDetailVOs) {
                        if (StringUtils.isNotEmpty(loanRepayDetailVO.getRpyNo())&&loanRepayDetailVO.getRpyNo().equals(hjRpayDetaillInfArry.getRpyNo())) {
                            continue;
                        }
                    }
                }*/
                if (hjRpayDetaillInfArry.getRpyAmt().doubleValue() > 0) {
                    repayDetailArrs.add(c2DetailArr(hjRpayDetaillInfArry, loanRepayDetailVOs));
                }
            }
        }
        respPersonalRepayDetail.setRetCode(RespRetCode.SUCCESS.getCode());
        respPersonalRepayDetail.setRetMsg("查询成功");
        respPersonalRepayDetail.setRepayDetailArr(repayDetailArrs);
    }

}
